package com.gxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxh.constant.MessageConstant;
import com.gxh.dto.LocationDTO;
import com.gxh.dto.LocationPageQueryDTO;
import com.gxh.entity.Location;
import com.gxh.exception.DeletionNotAllowedException;
import com.gxh.mapper.LocationMapper;
import com.gxh.mapper.MachineMapper;
import com.gxh.result.PageResult;
import com.gxh.service.LocationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LocationServiceImpl implements LocationService {

    @Autowired
    private LocationMapper locationMapper;
    @Autowired
    private MachineMapper machineMapper;
    /**
     * 分页查询
     * @param locationPageQueryDTO
     * @return
     */
    public PageResult pageQuery(LocationPageQueryDTO locationPageQueryDTO) {
        PageHelper.startPage(locationPageQueryDTO.getPage(), locationPageQueryDTO.getPageSize());
        Page<Location> page = locationMapper.pageQuery(locationPageQueryDTO);
        long total = page.getTotal();
        List records = page.getResult();
        return new PageResult(total, records);
    }


    /**
     * 新增
     * @param locationDTO
     */
    public void save(LocationDTO locationDTO) {
        Location location = new Location();
        BeanUtils.copyProperties(locationDTO, location);
        locationMapper.insertLocation(location);
    }


    /**
     * 修改位置
     * @param locationDTO
     */
    public void update(LocationDTO locationDTO) {
        Location location = new Location();
        BeanUtils.copyProperties(locationDTO, location);
        locationMapper.updateLocation(location);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {
        //判断位置下是否有设备
        for (Long id : ids) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("location_id", id);
            if (machineMapper.selectCount(queryWrapper) > 0) {
                throw new DeletionNotAllowedException(MessageConstant.LOCATION_BE_RELATED_BY_MACHINE);
            }
        }
        //删除位置
        locationMapper.deleteBatchIds(ids);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public Location getById(Long id) {
        QueryWrapper<Location> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Location location = locationMapper.selectOne(queryWrapper);
        return location;
    }

    /**
     * 查询所有位置
     * @return
     */
    public List<Location> list() {
        List<Location> locations = locationMapper.selectList(null);
        return locations;
    }
}
